Test Setup Failed
Pull Request — master (#857)
by
unknown
12:21
created

script.js ➔ goTo   A

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
dl 0
loc 4
rs 10
1
var lfm_route = location.origin + location.pathname;
2
var show_list;
3
var sort_type = 'alphabetic';
4
var multi_selection_enabled = false;
5
var selected = [];
6
var items = [];
7
8
$.fn.fab = function (options) {
9
  var menu = this;
10
  menu.addClass('fab-wrapper');
11
12
  var toggler = $('<a>')
13
    .addClass('fab-button fab-toggle')
14
    .append($('<i>').addClass('fas fa-plus'))
15
    .click(function () {
16
      menu.toggleClass('fab-expand');
17
    });
18
19
  menu.append(toggler);
20
21
  options.buttons.forEach(function (button) {
22
    toggler.before(
23
      $('<a>').addClass('fab-button fab-action')
24
        .attr('data-label', button.label)
25
        .attr('id', button.attrs.id)
26
        .append($('<i>').addClass(button.icon))
27
        .click(function () {
28
          menu.removeClass('fab-expand');
29
        })
30
    );
31
  });
32
};
33
34
$(document).ready(function () {
35
  $('#fab').fab({
36
    buttons: [
37
      {
38
        icon: 'fas fa-upload',
39
        label: lang['nav-upload'],
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
40
        attrs: {id: 'upload'}
41
      },
42
      {
43
        icon: 'fas fa-folder',
44
        label: lang['nav-new'],
45
        attrs: {id: 'add-folder'}
46
      }
47
    ]
48
  });
49
50
  actions.reverse().forEach(function (action) {
0 ignored issues
show
Bug introduced by
The variable actions seems to be never declared. If this is a global, consider adding a /** global: actions */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
51
    $('#nav-buttons > ul').prepend(
52
      $('<li>').addClass('nav-item').append(
53
        $('<a>').addClass('nav-link d-none')
54
          .attr('data-action', action.name)
55
          .attr('data-multiple', action.multiple)
56
          .append($('<i>').addClass('fas fa-fw fa-' + action.icon))
57
          .append($('<span>').text(action.label))
58
      )
59
    );
60
  });
61
62
  sortings.forEach(function (sort) {
0 ignored issues
show
Bug introduced by
The variable sortings seems to be never declared. If this is a global, consider adding a /** global: sortings */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
63
    $('#nav-buttons .dropdown-menu').append(
64
      $('<a>').addClass('dropdown-item').attr('data-sortby', sort.by)
65
        .append($('<i>').addClass('fas fa-fw fa-' + sort.icon))
66
        .append($('<span>').text(sort.label))
67
        .click(function() {
68
          sort_type = sort.by;
69
          loadItems();
70
        })
71
    );
72
  });
73
74
  loadFolders();
75
  performLfmRequest('errors')
76
    .done(function (response) {
77
      JSON.parse(response).forEach(function (message) {
78
        $('#alerts').append(
79
          $('<div>').addClass('alert alert-warning')
80
            .append($('<i>').addClass('fas fa-exclamation-circle'))
81
            .append(' ' + message)
82
        );
83
      });
84
    });
85
86
  $(window).on('dragenter', function(){
87
    $('#uploadModal').modal('show');
88
  });
89
90
  if (usingWysiwygEditor()) {
91
    $('#multi_selection_toggle').hide();
92
  }
93
});
94
95
// ======================
96
// ==  Navbar actions  ==
97
// ======================
98
99
$('#multi_selection_toggle').click(function () {
100
  multi_selection_enabled = !multi_selection_enabled;
101
102
  $('#multi_selection_toggle i')
103
    .toggleClass('fa-times', multi_selection_enabled)
104
    .toggleClass('fa-check-double', !multi_selection_enabled);
105
106
  if (!multi_selection_enabled) {
107
    clearSelected();
108
  }
109
});
110
111
$('#to-previous').click(function () {
112
  var previous_dir = getPreviousDir();
113
  if (previous_dir == '') return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
114
  goTo(previous_dir);
115
});
116
117
function toggleMobileTree(should_display) {
118
  if (should_display === undefined) {
119
    should_display = !$('#tree').hasClass('in');
120
  }
121
  $('#tree').toggleClass('in', should_display);
122
}
123
124
$('#show_tree').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
125
  toggleMobileTree();
126
});
127
128
$('#main').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
129
  if ($('#tree').hasClass('in')) {
130
    toggleMobileTree(false);
131
  }
132
});
133
134
$(document).on('click', '#add-folder', function () {
135
  dialog(lang['message-name'], '', createFolder);
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
});
137
138
$(document).on('click', '#upload', function () {
139
  $('#uploadModal').modal('show');
140
});
141
142
$(document).on('click', '[data-display]', function() {
143
  show_list = $(this).data('display');
144
  loadItems();
145
});
146
147
$(document).on('click', '[data-action]', function() {
148
  window[$(this).data('action')]($(this).data('multiple') ? getSelectedItems() : getOneSelectedElement());
149
});
150
151
// ==========================
152
// ==  Multiple Selection  ==
153
// ==========================
154
155
function toggleSelected (e) {
156
  if (!multi_selection_enabled) {
157
    selected = [];
158
  }
159
160
  var sequence = $(e.target).closest('a').data('id');
161
  var element_index = selected.indexOf(sequence);
162
  if (element_index === -1) {
163
    selected.push(sequence);
164
  } else {
165
    selected.splice(element_index, 1);
166
  }
167
168
  updateSelectedStyle();
169
}
170
171
function clearSelected () {
172
  selected = [];
173
174
  multi_selection_enabled = false;
175
176
  updateSelectedStyle();
177
}
178
179
function updateSelectedStyle() {
180
  items.forEach(function (item, index) {
181
    $('[data-id=' + index + ']')
182
      .find('.square')
183
      .toggleClass('selected', selected.indexOf(index) > -1);
184
  });
185
  toggleActions();
186
}
187
188
function getOneSelectedElement(orderOfItem) {
189
  var index = orderOfItem !== undefined ? orderOfItem : selected[0];
190
  return items[index];
191
}
192
193
function getSelectedItems() {
194
  return selected.reduce(function (arr_objects, id) {
195
    arr_objects.push(getOneSelectedElement(id));
196
    return arr_objects
197
  }, []);
198
}
199
200
function toggleActions() {
201
  var one_selected = selected.length === 1;
202
  var many_selected = selected.length >= 1;
203
  var only_image = getSelectedItems()
204
    .filter(function (item) { return !item.is_image; })
205
    .length === 0;
206
  var only_file = getSelectedItems()
207
    .filter(function (item) { return !item.is_file; })
208
    .length === 0;
209
210
  $('[data-action=use]').toggleClass('d-none', !(many_selected && only_file));
211
  $('[data-action=rename]').toggleClass('d-none', !one_selected);
212
  $('[data-action=preview]').toggleClass('d-none', !(many_selected && only_file));
213
  $('[data-action=move]').toggleClass('d-none', !many_selected);
214
  $('[data-action=download]').toggleClass('d-none', !(many_selected && only_file));
215
  $('[data-action=resize]').toggleClass('d-none', !(one_selected && only_image));
216
  $('[data-action=crop]').toggleClass('d-none', !(one_selected && only_image));
217
  $('[data-action=trash]').toggleClass('d-none', !many_selected);
218
  $('[data-action=open]').toggleClass('d-none', !one_selected || only_file);
219
  $('#multi_selection_toggle').toggleClass('d-none', usingWysiwygEditor() || !many_selected);
220
  $('#actions').toggleClass('d-none', selected.length === 0);
221
  $('#fab').toggleClass('d-none', selected.length !== 0);
222
}
223
224
// ======================
225
// ==  Folder actions  ==
226
// ======================
227
228
$(document).on('click', '#tree a', function (e) {
229
  goTo($(e.target).closest('a').data('path'));
230
  toggleMobileTree(false);
231
});
232
233
function goTo(new_dir) {
234
  $('#working_dir').val(new_dir);
235
  loadItems();
236
}
237
238
function getPreviousDir() {
239
  var working_dir = $('#working_dir').val();
240
  return working_dir.substring(0, working_dir.lastIndexOf('/'));
241
}
242
243
function setOpenFolders() {
244
  $('#tree [data-path]').each(function (index, folder) {
245
    // close folders that are not parent
246
    var should_open = ($('#working_dir').val() + '/').startsWith($(folder).data('path') + '/');
247
    $(folder).children('i')
248
      .toggleClass('fa-folder-open', should_open)
249
      .toggleClass('fa-folder', !should_open);
250
  });
251
252
  $('#tree .nav-item').removeClass('active');
253
  $('#tree [data-path="' + $('#working_dir').val() + '"]').parent('.nav-item').addClass('active');
254
}
255
256
// ====================
257
// ==  Ajax actions  ==
258
// ====================
259
260
function performLfmRequest(url, parameter, type) {
261
  var data = defaultParameters();
262
263
  if (parameter != null) {
0 ignored issues
show
Best Practice introduced by
Comparing parameter to null using the != operator is not safe. Consider using !== instead.
Loading history...
264
    $.each(parameter, function (key, value) {
265
      data[key] = value;
266
    });
267
  }
268
269
  return $.ajax({
270
    type: 'GET',
271
    beforeSend: function(request) {
272
      var token = getUrlParam('token');
273
      if (token !== null) {
274
        request.setRequestHeader("Authorization", 'Bearer ' + token);
275
      }
276
    },
277
    dataType: type || 'text',
278
    url: lfm_route + '/' + url,
279
    data: data,
280
    cache: false
281
  }).fail(function (jqXHR, textStatus, errorThrown) {
0 ignored issues
show
Unused Code introduced by
The parameter textStatus is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter errorThrown is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
282
    displayErrorResponse(jqXHR);
283
  });
284
}
285
286
function displayErrorResponse(jqXHR) {
287
  notify('<div style="max-height:50vh;overflow: scroll;">' + jqXHR.responseText + '</div>');
288
}
289
290
var refreshFoldersAndItems = function (data) {
291
  loadFolders();
292
  if (data != 'OK') {
293
    data = Array.isArray(data) ? data.join('<br/>') : data;
294
    notify(data);
295
  }
296
};
297
298
var hideNavAndShowEditor = function (data) {
299
  $('#nav-buttons > ul').addClass('d-none');
300
  $('#content').html(data);
301
  $('#pagination').removeClass('preserve_actions_space')
302
  clearSelected();
303
}
304
305
function loadFolders() {
306
  performLfmRequest('folders', {}, 'html')
307
    .done(function (data) {
308
      $('#tree').html(data);
309
      loadItems();
310
    });
311
}
312
313
function generatePaginationHTML(el, args) {
314
  var template = '<li class="page-item"><\/li>';
315
  var linkTemplate = '<a class="page-link"><\/a>';
316
  var currentPage = args.currentPage;
317
  var totalPage = args.totalPage;
318
  var rangeStart = args.rangeStart;
319
  var rangeEnd = args.rangeEnd;
320
  var i;
321
322
  // Disable page range, display all the pages
323
  if (args.pageRange === null) {
324
    for (i = 1; i <= totalPage; i++) {
325
      var button = $(template)
326
        .attr('data-num', i)
327
        .append($(linkTemplate).html(i));
328
      if (i == currentPage) {
329
        button.addClass('active');
330
      }
331
      el.append(button);
332
    }
333
334
    return;
335
  }
336
337
  if (rangeStart <= 3) {
338
    for (i = 1; i < rangeStart; i++) {
339
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
340
        .attr('data-num', i)
341
        .append($(linkTemplate).html(i));
342
      if (i == currentPage) {
343
        button.addClass('active');
344
      }
345
      el.append(button);
346
    }
347
  } else {
348
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
349
      .attr('data-num', 1)
350
      .append($(linkTemplate).html(1));
351
    el.append(button);
352
353
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
354
      .addClass('disabled')
355
      .append($(linkTemplate).html('...'));
356
    el.append(button);
357
  }
358
359
  for (i = rangeStart; i <= rangeEnd; i++) {
360
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
361
      .attr('data-num', i)
362
      .append($(linkTemplate).html(i));
363
    if (i == currentPage) {
364
      button.addClass('active');
365
    }
366
    el.append(button);
367
  }
368
369
  if (rangeEnd >= totalPage - 2) {
370
    for (i = rangeEnd + 1; i <= totalPage; i++) {
371
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
372
        .attr('data-num', i)
373
        .append($(linkTemplate).html(i));
374
      el.append(button);
375
    }
376
  } else {
377
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
378
      .addClass('disabled')
379
      .append($(linkTemplate).html('...'));
380
    el.append(button);
381
382
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
383
      .attr('data-num', totalPage)
384
      .append($(linkTemplate).html(totalPage));
385
    el.append(button);
386
  }
387
}
388
389
function createPagination(paginationSetting) {
390
  var el = $('<ul class="pagination" role="navigation"></ul>');
391
392
  var currentPage = paginationSetting.current_page;
393
  var pageRange = 5;
394
  var totalPage = Math.ceil(paginationSetting.total / paginationSetting.per_page);
395
396
  var rangeStart = currentPage - pageRange;
397
  var rangeEnd = currentPage + pageRange;
398
399
  if (rangeEnd > totalPage) {
400
    rangeEnd = totalPage;
401
    rangeStart = totalPage - pageRange * 2;
402
    rangeStart = rangeStart < 1 ? 1 : rangeStart;
403
  }
404
405
  if (rangeStart <= 1) {
406
    rangeStart = 1;
407
    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
408
  }
409
410
  generatePaginationHTML(el, {
411
    totalPage: totalPage,
412
    currentPage: currentPage,
413
    pageRange: pageRange,
414
    rangeStart: rangeStart,
415
    rangeEnd: rangeEnd
416
  });
417
418
  $('#pagination').append(el);
419
}
420
421
function loadItems(page) {
422
  loading(true);
423
  performLfmRequest('jsonitems', {show_list: show_list, sort_type: sort_type, page: page || 1}, 'html')
424
    .done(function (data) {
425
      selected = [];
426
      var response = JSON.parse(data);
427
      var working_dir = response.working_dir;
428
      items = response.items;
429
      var hasItems = items.length !== 0;
430
      var hasPaginator = !!response.paginator;
431
      $('#empty').toggleClass('d-none', hasItems);
432
      $('#content').html('').removeAttr('class');
433
      $('#pagination').html('').removeAttr('class');
434
435
      if (hasItems) {
436
        $('#content').addClass(response.display);
437
        $('#pagination').addClass('preserve_actions_space');
438
439
        items.forEach(function (item, index) {
440
          var template = $('#item-template').clone()
441
            .removeAttr('id class')
442
            .attr('data-id', index)
443
            .click(toggleSelected)
444
            .dblclick(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
445
              if (item.is_file) {
446
                use(getSelectedItems());
447
              } else {
448
                goTo(item.url);
449
              }
450
            });
451
452
          if (item.thumb_url) {
453
            var image = $('<div>').css('background-image', 'url("' + item.thumb_url + '?timestamp=' + item.time + '")');
454
          } else {
455
            var image = $('<div>').addClass('mime-icon ico-' + item.icon);
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable image already seems to be declared on line 453. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
456
          }
457
458
          template.find('.square').append(image);
459
          template.find('.item_name').text(item.name);
460
          template.find('time').text((new Date(item.time * 1000)).toLocaleString());
461
462
          $('#content').append(template);
463
        });
464
      }
465
466
      if (hasPaginator) {
467
        createPagination(response.paginator);
468
469
        $('#pagination a').on('click', function(event) {
470
          event.preventDefault();
471
472
          loadItems($(this).closest('li')[0].getAttribute('data-num'));
473
474
          return false;
475
        });
476
      }
477
478
      $('#nav-buttons > ul').removeClass('d-none');
479
480
      $('#working_dir').val(working_dir);
481
      console.log('Current working_dir : ' + working_dir);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
482
      var breadcrumbs = [];
483
      var validSegments = working_dir.split('/').filter(function (e) { return e; });
484
      validSegments.forEach(function (segment, index) {
485
        if (index === 0) {
486
          // set root folder name as the first breadcrumb
487
          breadcrumbs.push($("[data-path='/" + segment + "']").text());
488
        } else {
489
          breadcrumbs.push(segment);
490
        }
491
      });
492
493
      $('#current_folder').text(breadcrumbs[breadcrumbs.length - 1]);
494
      $('#breadcrumbs > ol').html('');
495
      breadcrumbs.forEach(function (breadcrumb, index) {
496
        var li = $('<li>').addClass('breadcrumb-item').text(breadcrumb);
497
498
        if (index === breadcrumbs.length - 1) {
499
          li.addClass('active').attr('aria-current', 'page');
500
        } else {
501
          li.click(function () {
502
            // go to corresponding path
503
            goTo('/' + validSegments.slice(0, 1 + index).join('/'));
504
          });
505
        }
506
507
        $('#breadcrumbs > ol').append(li);
508
      });
509
510
      var atRootFolder = getPreviousDir() == '';
511
      $('#to-previous').toggleClass('d-none invisible-lg', atRootFolder);
512
      $('#show_tree').toggleClass('d-none', !atRootFolder).toggleClass('d-block', atRootFolder);
513
      setOpenFolders();
514
      loading(false);
515
      toggleActions();
516
    });
517
}
518
519
function loading(show_loading) {
520
  $('#loading').toggleClass('d-none', !show_loading);
521
}
522
523
function createFolder(folder_name) {
524
  performLfmRequest('newfolder', {name: folder_name})
525
    .done(refreshFoldersAndItems);
526
}
527
528
// ==================================
529
// ==         File Actions         ==
530
// ==================================
531
532
function rename(item) {
533
  dialog(lang['message-rename'], item.name, function (new_name) {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
534
    performLfmRequest('rename', {
535
      file: item.name,
536
      new_name: new_name
537
    }).done(refreshFoldersAndItems);
538
  });
539
}
540
541
function trash(items) {
542
  notify(lang['message-delete'], function () {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
543
    performLfmRequest('delete', {
544
      items: items.map(function (item) { return item.name; })
545
    }).done(refreshFoldersAndItems)
546
  });
547
}
548
549
function crop(item) {
550
  performLfmRequest('crop', {img: item.name})
551
    .done(hideNavAndShowEditor);
552
}
553
554
function resize(item) {
555
  performLfmRequest('resize', {img: item.name})
556
    .done(hideNavAndShowEditor);
557
}
558
559
function download(items) {
560
  items.forEach(function (item, index) {
561
    var data = defaultParameters();
562
563
    data['file'] = item.name;
564
565
    var token = getUrlParam('token');
566
    if (token) {
567
      data['token'] = token;
568
    }
569
570
    setTimeout(function () {
571
      location.href = lfm_route + '/download?' + $.param(data);
572
    }, index * 100);
573
  });
574
}
575
576
function open(item) {
577
  goTo(item.url);
578
}
579
580
function preview(items) {
581
  var carousel = $('#carouselTemplate').clone().attr('id', 'previewCarousel').removeClass('d-none');
582
  var imageTemplate = carousel.find('.carousel-item').clone().removeClass('active');
583
  var indicatorTemplate = carousel.find('.carousel-indicators > li').clone().removeClass('active');
584
  carousel.children('.carousel-inner').html('');
585
  carousel.children('.carousel-indicators').html('');
586
  carousel.children('.carousel-indicators,.carousel-control-prev,.carousel-control-next').toggle(items.length > 1);
587
588
  items.forEach(function (item, index) {
589
    var carouselItem = imageTemplate.clone()
590
      .addClass(index === 0 ? 'active' : '');
591
592
    if (item.thumb_url) {
593
      carouselItem.find('.carousel-image').css('background-image', 'url(\'' + item.url + '?timestamp=' + item.time + '\')');
594
    } else {
595
      carouselItem.find('.carousel-image').css('width', '50vh').append($('<div>').addClass('mime-icon ico-' + item.icon));
596
    }
597
598
    carouselItem.find('.carousel-label').attr('target', '_blank').attr('href', item.url)
599
      .append(item.name)
600
      .append($('<i class="fas fa-external-link-alt ml-2"></i>'));
601
602
    carousel.children('.carousel-inner').append(carouselItem);
603
604
    var carouselIndicator = indicatorTemplate.clone()
605
      .addClass(index === 0 ? 'active' : '')
606
      .attr('data-slide-to', index);
607
    carousel.children('.carousel-indicators').append(carouselIndicator);
608
  });
609
610
611
  // carousel swipe control
612
  var touchStartX = null;
613
614
  carousel.on('touchstart', function (event) {
615
    var e = event.originalEvent;
616
    if (e.touches.length == 1) {
0 ignored issues
show
Best Practice introduced by
Comparing e.touches.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
617
      var touch = e.touches[0];
618
      touchStartX = touch.pageX;
619
    }
620
  }).on('touchmove', function (event) {
621
    var e = event.originalEvent;
622
    if (touchStartX != null) {
0 ignored issues
show
Best Practice introduced by
Comparing touchStartX to null using the != operator is not safe. Consider using !== instead.
Loading history...
623
      var touchCurrentX = e.changedTouches[0].pageX;
624
      if ((touchCurrentX - touchStartX) > 60) {
625
        touchStartX = null;
626
        carousel.carousel('prev');
627
      } else if ((touchStartX - touchCurrentX) > 60) {
628
        touchStartX = null;
629
        carousel.carousel('next');
630
      }
631
    }
632
  }).on('touchend', function () {
633
    touchStartX = null;
634
  });
635
  // end carousel swipe control
636
637
  notify(carousel);
638
}
639
640
function move(items) {
641
  performLfmRequest('move', { items: items.map(function (item) { return item.name; }) })
642
    .done(refreshFoldersAndItems);
643
}
644
645
function getUrlParam(paramName) {
646
  var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
647
  var match = window.location.search.match(reParam);
648
  return ( match && match.length > 1 ) ? match[1] : null;
649
}
650
651
function use(items) {
652
  function useTinymce3(url) {
653
    if (!usingTinymce3()) { return; }
654
655
    var win = tinyMCEPopup.getWindowArg("window");
0 ignored issues
show
Bug introduced by
The variable tinyMCEPopup seems to be never declared. If this is a global, consider adding a /** global: tinyMCEPopup */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
656
    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
657
    if (typeof(win.ImageDialog) != "undefined") {
658
      // Update image dimensions
659
      if (win.ImageDialog.getImageData) {
660
        win.ImageDialog.getImageData();
661
      }
662
663
      // Preview if necessary
664
      if (win.ImageDialog.showPreviewImage) {
665
        win.ImageDialog.showPreviewImage(url);
666
      }
667
    }
668
    tinyMCEPopup.close();
669
  }
670
671
  function useTinymce4AndColorbox(url) {
672
    if (!usingTinymce4AndColorbox()) { return; }
673
674
    parent.document.getElementById(getUrlParam('field_name')).value = url;
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
675
676
    if(typeof parent.tinyMCE !== "undefined") {
677
      parent.tinyMCE.activeEditor.windowManager.close();
678
    }
679
    if(typeof parent.$.fn.colorbox !== "undefined") {
680
      parent.$.fn.colorbox.close();
681
    }
682
  }
683
684
  function useCkeditor3(url) {
685
    if (!usingCkeditor3()) { return; }
686
687
    if (window.opener) {
688
      // Popup
689
      window.opener.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
690
    } else {
691
      // Modal (in iframe)
692
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
693
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorCleanUpFuncNum'));
694
    }
695
  }
696
697
  function useFckeditor2(url) {
698
    if (!usingFckeditor2()) { return; }
699
700
    var p = url;
701
    var w = data['Properties']['Width'];
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
702
    var h = data['Properties']['Height'];
703
    window.opener.SetUrl(p,w,h);
704
  }
705
706
  var url = items[0].url;
707
  var callback = getUrlParam('callback');
708
  var useFileSucceeded = true;
709
710
  if (usingWysiwygEditor()) {
711
    useTinymce3(url);
712
713
    useTinymce4AndColorbox(url);
714
715
    useCkeditor3(url);
716
717
    useFckeditor2(url);
718
  } else if (callback && window[callback]) {
719
    window[callback](getSelectedItems());
720
  } else if (callback && parent[callback]) {
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
721
    parent[callback](getSelecteditems());
722
  } else if (window.opener) { // standalone button or other situations
723
    window.opener.SetUrl(getSelectedItems());
724
  } else {
725
    useFileSucceeded = false;
726
  }
727
728
  if (useFileSucceeded) {
729
    if (window.opener) {
730
      window.close();
731
    }
732
  } else {
733
    console.log('window.opener not found');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
734
    // No editor found, open/download file using browser's default method
735
    window.open(url);
736
  }
737
}
738
//end useFile
739
740
// ==================================
741
// ==     WYSIWYG Editors Check    ==
742
// ==================================
743
744
function usingTinymce3() {
745
  return !!window.tinyMCEPopup;
746
}
747
748
function usingTinymce4AndColorbox() {
749
  return !!getUrlParam('field_name');
750
}
751
752
function usingCkeditor3() {
753
  return !!getUrlParam('CKEditor') || !!getUrlParam('CKEditorCleanUpFuncNum');
754
}
755
756
function usingFckeditor2() {
757
  return window.opener && typeof data != 'undefined' && data['Properties']['Width'] != '';
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
758
}
759
760
function usingWysiwygEditor() {
761
  return usingTinymce3() || usingTinymce4AndColorbox() || usingCkeditor3() || usingFckeditor2();
762
}
763
764
// ==================================
765
// ==            Others            ==
766
// ==================================
767
768
function defaultParameters() {
769
  return {
770
    working_dir: $('#working_dir').val(),
771
    type: $('#type').val()
772
  };
773
}
774
775
function notImp() {
776
  notify('Not yet implemented!');
777
}
778
779
function notify(body, callback) {
780
  $('#notify').find('.btn-primary').toggle(callback !== undefined);
781
  $('#notify').find('.btn-primary').unbind().click(callback);
782
  $('#notify').modal('show').find('.modal-body').html(body);
783
}
784
785
function dialog(title, value, callback) {
786
  $('#dialog').find('input').val(value);
787
  $('#dialog').on('shown.bs.modal', function () {
788
    $('#dialog').find('input').focus();
789
  });
790
  $('#dialog').find('.btn-primary').unbind().click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
791
    callback($('#dialog').find('input').val());
792
  });
793
  $('#dialog').modal('show').find('.modal-title').text(title);
794
}
795